package com.gateway.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Mono;

/**
 * 自定义全局过滤器，无需在配置文件中配置
 * 
 * @author gzp
 *
 */
@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {

	/**
	 * 过滤器执行顺序方法
	 */
	@Override
	public int getOrder() {
		// 值越小越先执行
		return 1;
	}

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		System.out.println("-----------全局过滤器MyGlobalFilter-----------");
		String token = exchange.getRequest().getQueryParams().getFirst("token");
		if (StringUtils.isEmpty(token)) {
			// 设置响应状态码为未授权
			exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
			return exchange.getResponse().setComplete();
		}
		return chain.filter(exchange);
	}

}
